// pages/search/search.js
import evn from "../../utils/http/evn"
import { apiGetBizSchoolsPublic, apiGetDicPublic,apiGetProfessionsBySearch } from '../../utils/http/api'
const dictionary = wx.getStorageSync('dictionary')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: evn.dev.baseUrl,
    dictionary,
    visibleNav: false, // 搜索显示隐藏
    valueNav: '', // 搜索框值
    datas: [], //查询结果
    loadingFlag: false,
    currIndex: 0, // 当前选中的标签：0-院校匹配，1-项目匹配
    pageNum: 1,
    pageSize: 10,
    windowHeight: 0,
    pages: 0,
    list: [],
    imgBaseUrl:  evn.dev.imgUrl,
    tabValue: 0, // 当前标签页：0-院校匹配，1-项目匹配
    degree_type: {
      value: '',
      options: [
        {
          value: '',
          label: '不限',
        },
        {
          value: '1',
          label: '本科',
        },
        {
          value: '2',
          label: '硕士',
        },
        {
          value: '3',
          label: '博士',
        },
        {
          value: '4',
          label: '专家',
        },
      ],
    },
    teach_language: {
      value: '',
      options: [
        {
          value: '',
          label: '不限',
        },
        {
          value: '1',
          label: '俄语教学',
        },
        {
          value: '2',
          label: '英语教学',
        },
        {
          value: '3',
          label: '双语教学',
        },
      ],
    },
    training_plan: {
      value: '',
      options: [
        { value: '', label: '不限' },
        { value: '1', label: '高升本' },
        { value: '2', label: '本升硕' }, // 新增
        { value: '3', label: '专升硕' },
        { value: '4', label: '硕升博' },
        { value: '5', label: '专升本' }
      ]
    },
    destination: {
      value: '',
      options: []
    },
    start_time: {
      value: '',
      options: []
    },
    degreeValue: '',
    teachLanguageValue: '',
    trainingPlanValue: '',
    destinationValue: '',
    startTimeValue: '',
    // 下拉框展开状态
    trainingPlanDropdownOpen: false,
    destinationDropdownOpen: false,
    // 项目匹配下拉框状态
    projectTrainingPlanDropdownOpen: false,
    projectDestinationDropdownOpen: false,
    projectStartTimeDropdownOpen: false,
    // 胶囊按钮相关
    capsuleTop: 0, // 胶囊按钮顶部
    capsuleHeight: 0, // 胶囊按钮高度
    capsuleRight: 0, // 胶囊按钮右侧
    capsuleWidth: 0, // 胶囊按钮宽度
    navBarHeight: 0, // 自定义导航栏高度
    hasMore: true, // 是否还有更多数据
    searchActive: false, // 控制内容区域显示
  },

  onDegreeChange(e) {
    this.setData({
      degreeValue: e.detail.value,
      'degree_type.value': e.detail.value,
      pageNum: 1,
      list: []
    });
    // 任何选择都触发搜索（包括"不限"）
    if(this.data.valueNav.trim() !== '') {
      this.switchInt();
    }
  },

  onTeachLanguageChange(e) {
    this.setData({
      teachLanguageValue: e.detail.value,
      'teach_language.value': e.detail.value,
      pageNum: 1,
      list: []
    });
    // 任何选择都触发搜索（包括"不限"）
    if(this.data.valueNav.trim() !== '') {
      this.switchInt();
    }
  },

  onTrainingPlanChange(e) {
    this.setData({
      trainingPlanValue: e.detail.value,
      'training_plan.value': e.detail.value,
      pageNum: 1,
      list: []
    });
    
    // 任何选择都触发搜索（包括"不限"）
    this.switchInt();
  },

  onDestinationChange(e) {
    this.setData({
      destinationValue: e.detail.value,
      'destination.value': e.detail.value,
      pageNum: 1,
      list: []
    });
    
    // 任何选择都触发搜索（包括"不限"）
    this.switchInt();
  },

  onStartTimeChange(e) {
    this.setData({
      startTimeValue: e.detail.value,
      'start_time.value': e.detail.value,
      pageNum: 1,
      list: []
    });
    
    // 任何选择都触发搜索（包括"不限"）
    this.switchInt();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取系统信息，设置状态栏高度
    const systemInfo = wx.getSystemInfoSync();
   // 获取状态栏高度
const statusBarHeight = systemInfo.statusBarHeight || 44;

// 获取胶囊按钮信息（如需在页面用胶囊位置，这部分保留）
let menuButtonInfo = { top: 0, height: 32, right: 0, width: 87 };
if (wx.getMenuButtonBoundingClientRect) {
  try {
    menuButtonInfo = wx.getMenuButtonBoundingClientRect();
  } catch (e) {}
}

// 直接设置自定义导航栏高度为你设计的值，比如80
const navbarHeight = 40; 

this.setData({
  capsuleTop: menuButtonInfo.top,
  capsuleHeight: menuButtonInfo.height,
  capsuleRight: menuButtonInfo.right,
  capsuleWidth: menuButtonInfo.width,
  navBarHeight: navbarHeight 
});
    // 设置CSS变量
    wx.nextTick(() => {
      const query = wx.createSelectorQuery();
      query.select('page').boundingClientRect();
      query.exec((res) => {
        if (res[0]) {
          // 设置状态栏高度CSS变量
          const style = `--status-bar-height: ${statusBarHeight}px;`;
          wx.setPageStyle && wx.setPageStyle(style);
        }
      });
    });

    wx.pageScrollTo({
      scrollTop: 0
    });

    // 显示加载状态
    wx.showLoading({
      title: '加载字典数据...',
      mask: true
    });

    // 初始化字典数据
    this.initDictionaryData();
    // 页面初次进入时不自动搜索，list为空
    this.setData({ list: [] });
  },

  // 初始化字典数据
  initDictionaryData() {
    let loadedCount = 0;
    const totalDicts = 3; // 需要加载的字典数量：培养计划、目的地、开学时间
    
    const checkAllLoaded = () => {
      loadedCount++;
      if (loadedCount >= totalDicts) {
        wx.hideLoading();
        // 字典数据加载完成后，不自动触发搜索
        // this.switchInt(); // 注释掉自动搜索
      }
    };
    
    // 获取培养计划字典
    this.loadTrainingPlanDict(checkAllLoaded);
    
    // 获取目的地字典
    this.loadDestinationDict(checkAllLoaded);
    
    // 获取开学时间字典
    this.loadStartTimeDict(checkAllLoaded);
  },

  // 加载培养计划字典
  loadTrainingPlanDict(callback) {
    apiGetDicPublic({ dicType: 'edu_plans' }).then((res) => {
      // 检查是否是认证错误
      if (res.code === 401) {
        wx.showToast({
          title: '字典数据加载失败',
          icon: 'none'
        });
        callback && callback();
        return;
      }
      
      // 处理响应数据
      let dicData = res.data || res.rows || res.list || [];
      let trainingPlanOptions = [
        {
          value: '',
          label: '不限'
        }
      ];
      let eduPlansList = [
        {
          value: '',
          label: '不限'
        }
      ];
      
      if (Array.isArray(dicData) && dicData.length > 0) {
        // 只显示edu_plans类型的字典项
        dicData.forEach((item) => {
          // 检查是否为edu_plans类型的字典项
          if (item.dictType === 'edu_plans' || item.type === 'edu_plans') {
            let dictLabel = item.dictLabel || item.label || item.name || item.title || item.text;
            let dictValue = item.dictValue || item.value || item.id || item.dictCode || dictLabel;
            
            if (dictLabel) {
              trainingPlanOptions.push({
                value: dictValue,
                label: dictLabel
              });
              eduPlansList.push({
                value: dictValue,
                label: dictLabel
              });
            }
          }
        });
      }
      
      // 设置选项，默认选中"不限"
      this.setData({
        'training_plan.options': trainingPlanOptions,
        'training_plan.value': '',
        trainingPlanValue: '',
        'dictionary.eduPlansList': eduPlansList
      });
      
      callback && callback();
    }).catch((err) => {
      console.error('获取培养计划字典失败:', err);
      wx.showToast({
        title: '培养计划数据加载失败',
        icon: 'none'
      });
      callback && callback();
    });

    apiGetDicPublic({ dicType: 'teachlanguage' }).then((res) => {
      this.setData({
        'dictionary.languageList': res.data
      });
    })
      
  },

  // 加载目的地字典
  loadDestinationDict(callback) {
    apiGetDicPublic({ type: 'place' }).then((res) => {
      // 检查是否是认证错误
      if (res.code === 401) {
        wx.showToast({
          title: '字典数据加载失败',
          icon: 'none'
        });
        callback && callback();
        return;
      }
      
      // 处理响应数据
      let dicData = res.data || res.rows || res.list || [];
      let destinationOptions = [
        {
          value: '',
          label: '不限'
        }
      ];
      let addrList = [
        {
          value: '',
          label: '不限'
        }
      ];
      
      if (Array.isArray(dicData) && dicData.length > 0) {
        // 显示所有place类型的字典项
        dicData.forEach((item) => {
          // 检查是否为place类型的字典项
          if (item.dictType === 'place' || item.type === 'place') {
            let dictLabel = item.dictLabel || item.label || item.name || item.title || item.text;
            let dictValue = item.dictValue || item.value || item.id || item.dictCode || dictLabel;
            
            if (dictLabel) {
              destinationOptions.push({
                value: dictValue,
                label: dictLabel
              });
              addrList.push({
                value: dictValue,
                label: dictLabel
              });
            }
          }
        });
      }
      
      // 设置选项，默认选中"不限"
      this.setData({
        'destination.options': destinationOptions,
        'destination.value': '',
        destinationValue: '',
        'dictionary.addrList': addrList
      });
    }).catch((err) => {
      console.error('获取目的地字典失败:', err);
      wx.showToast({
        title: '目的地数据加载失败',
        icon: 'none'
      });
    }).finally(() => {
      callback && callback();
    });
  },

  // 加载开学时间字典
  loadStartTimeDict(callback) {
    apiGetDicPublic({ type: 'edu_plan' }).then((res) => {
      // 检查是否是认证错误
      if (res.code === 401) {
        wx.showToast({
          title: '字典数据加载失败',
          icon: 'none'
        });
        callback && callback();
        return;
      }
      
      // 处理响应数据
      let dicData = res.data || res.rows || res.list || [];
     let startTimeOptions = [
  { value: '', label: '不限' },
  { value: '1', label: '春季开学' },
  { value: '2', label: '秋季开学' }
      ];
      let startTimeList = [
        {
          value: '',
          label: '不限'
        }
      ];
      
      if (Array.isArray(dicData) && dicData.length > 0) {
        // 显示所有edu_plan类型的字典项
        dicData.forEach((item) => {
          // 检查是否为edu_plan类型的字典项
          if (item.dictType === 'edu_plan' || item.type === 'edu_plan') {
            let dictLabel = item.dictLabel || item.label || item.name || item.title || item.text;
            let dictValue = item.dictValue || item.value || item.id || item.dictCode || dictLabel;
            
            if (dictLabel) {
              startTimeOptions.push({
                value: dictValue,
                label: dictLabel
              });
              startTimeList.push({
                value: dictValue,
                label: dictLabel
              });
            }
          }
        });
      }
      
      // 设置选项，默认选中"不限"
      this.setData({
        'start_time.options': startTimeOptions,
        'start_time.value': '',
        startTimeValue: '',
        'dictionary.startTimeList': startTimeList
      });
    }).catch((err) => {
      console.error('获取开学时间字典失败:', err);
      wx.showToast({
        title: '开学时间数据加载失败',
        icon: 'none'
      });
    }).finally(() => {
      callback && callback();
    });
  },
  

  goBack() {
    wx.navigateBack({
      delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页。默认为1。
    })
  },

  // 搜索
  switchInt() {
    // 重置页码和列表（仅第一页时）
    if(this.data.pageNum === 1){
      this.setData({
        list: []
      })
    }
    // 检查筛选条件
    const hasKeyword = this.data.valueNav.trim() !== '';
    const hasTrainingPlan = this.data.trainingPlanValue && this.data.trainingPlanValue !== '' && this.data.trainingPlanValue !== 'true' && this.data.trainingPlanValue !== 'false';
    const hasDestination = this.data.destinationValue && this.data.destinationValue !== '' && this.data.destinationValue !== 'true' && this.data.destinationValue !== 'false';
    const hasStartTime = this.data.startTimeValue && this.data.startTimeValue !== '' && this.data.startTimeValue !== 'true' && this.data.startTimeValue !== 'false';
    let hasAnyFilterCondition;

    if (!this.data.valueNav || this.data.valueNav.trim() === '') {
    // 清空列表
    this.setData({ list: [], datas: { list: [], total: 0 }, hasMore: false });
    wx.hideLoading && wx.hideLoading();
    return;
  }
    if(this.data.currIndex === 0 || this.data.currIndex === '0') {
      hasAnyFilterCondition = hasTrainingPlan || hasDestination;
    } else {
      hasAnyFilterCondition = hasTrainingPlan || hasDestination || hasStartTime;
    }

    // 清理无效布尔字符串
    let cleanedData = {};
    let needsUpdate = false;
    if (this.data.trainingPlanValue === 'true' || this.data.trainingPlanValue === 'false') {
      cleanedData.trainingPlanValue = '';
      needsUpdate = true;
    }
    if (this.data.destinationValue === 'true' || this.data.destinationValue === 'false') {
      cleanedData.destinationValue = '';
      needsUpdate = true;
    }
    if (this.data.startTimeValue === 'true' || this.data.startTimeValue === 'false') {
      cleanedData.startTimeValue = '';
      needsUpdate = true;
    }
    if (needsUpdate) {
      this.setData(cleanedData);
    }
    const currentTrainingPlan = needsUpdate && cleanedData.trainingPlanValue !== undefined ? cleanedData.trainingPlanValue : this.data.trainingPlanValue;
    const currentDestination = needsUpdate && cleanedData.destinationValue !== undefined ? cleanedData.destinationValue : this.data.destinationValue;
    const currentStartTime = needsUpdate && cleanedData.startTimeValue !== undefined ? cleanedData.startTimeValue : this.data.startTimeValue;
    const hasKeywordFinal = this.data.valueNav && this.data.valueNav.trim() !== '';
    const hasTrainingPlanFinal = currentTrainingPlan && currentTrainingPlan !== '';
    const hasDestinationFinal = currentDestination && currentDestination !== '';
    const hasStartTimeFinal = currentStartTime && currentStartTime !== '';
    // 构造搜索参数

    let params = {};
    if(this.data.currIndex === 0 || this.data.currIndex === '0') {
      if(hasKeywordFinal) params.name = this.data.valueNav.trim();
      if(hasTrainingPlanFinal) params.eduPlanId = currentTrainingPlan;
      if(hasDestinationFinal) params.placeId = currentDestination;
      params.pageNum = this.data.pageNum || 1;
      params.pageSize = this.data.pageSize || 10;
    } else if(this.data.currIndex === 1 || this.data.currIndex === '1') {
      if(hasKeywordFinal) params.name = this.data.valueNav.trim();
      if(hasTrainingPlanFinal) params.plan = String(currentTrainingPlan).trim();
      if(hasDestinationFinal) params.destination = String(currentDestination).trim();
      if(hasStartTimeFinal) params.startTime = String(currentStartTime).trim();
      params.pageNum = this.data.pageNum || 1;
      params.pageSize = this.data.pageSize || 10;
      if (params.plan === '' || params.plan === 'undefined' || params.plan === 'null') delete params.plan;
      if (params.destination === '' || params.destination === 'undefined' || params.destination === 'null') delete params.destination;
      if (params.startTime === '' || params.startTime === 'undefined' || params.startTime === 'null') delete params.startTime;
    }
    // 只输出核心分页参数日志
    console.log('[分页参数]', params);
    // 选择API
     params.isShow = 1; // 只显示已发布的
    //  if(params.name=='' || params.name ==null){
    //    return
    //  }
     // 显示加载状态
    wx.showLoading({ title: '搜索中...' });
    let apiMethod = (this.data.currIndex === 0 || this.data.currIndex === '0') ? apiGetBizSchoolsPublic(params) : apiGetProfessionsBySearch(params);
    apiMethod.then((res)=> {
      wx.hideLoading();
      let resultList = res.data || res.rows || res || [];
      let formattedList;
      if(this.data.currIndex === 0 || this.data.currIndex === '0') {
        formattedList = resultList.map((school, index) => {
          // 获取培养计划标签文本
          let eduPlanLabel = '';
          if (school.eduPlanId && this.data.training_plan.options) {
            const plan = this.data.training_plan.options.find(item => item.value == school.eduPlanId);
            eduPlanLabel = plan ? plan.label : '';
          }
          let eduPlanClass = '';
          // 1-高升本（橙），2-专升本（蓝），3-本升硕（绿），4-专升硕（紫），5-硕升博（红）
          if (school.eduPlanId == '1') eduPlanClass = 'edu-plan-gsb';
          else if (school.eduPlanId == '2') eduPlanClass = 'edu-plan-zsb';
          else if (school.eduPlanId == '3') eduPlanClass = 'edu-plan-bss';
          else if (school.eduPlanId == '4') eduPlanClass = 'edu-plan-zss';
          else if (school.eduPlanId == '5') eduPlanClass = 'edu-plan-ssb';

          // 处理开学时间标签，支持字符串/数组，不再去重，直接转数组
          let openingDates = school.openingDates;
          if (typeof openingDates === 'string') {
            openingDates = openingDates.split(',').filter(Boolean);
          }
          if (!Array.isArray(openingDates)) {
            openingDates = [];
          }
 // 只在院校匹配分支补充 placeName/cityName
          let placeName = '';
          let cityName = '';
          if (school.placeId && this.data.dictionary && Array.isArray(this.data.dictionary.addrList)) {
            const addr = this.data.dictionary.addrList.find(item => String(item.value) === String(school.placeId));
            if (addr) {
              placeName = addr.label || addr.name || '';
            }
          }
          // cityName 直接取 school.cityName 字段
          if (school.cityName) {
            cityName = school.cityName;
          }

        // intro 截断22字，超出加...
          let intro = school.intro || '';
          intro = this.filterHtmlTags(intro); // 过滤标签
          if (intro.length > 22) intro = intro.slice(0, 22) + '...';
          return {
            ID: school.id || index,
            chineseName: [school.name || '未知院校'],
            description: intro || '暂无介绍',
            logo: school.logo,
            pics: school.pics,
            name: school.name,
            placeName,
            cityName,
            intro: intro || '暂无介绍',
            placeId: school.placeId,
            eduPlanId: school.eduPlanId,
            openingDateId: school.openingDateId,
            openingDates,
            eduPlanClass // 新增
          }
        });
      } else {
        // 项目匹配：格式化专业数据
        formattedList = resultList.map((profession, index) => {
          let eduPlanLabel = '';
          if (profession.eduPlanId && this.data.training_plan.options) {
            const plan = this.data.training_plan.options.find(item => item.value == profession.eduPlanId);
            eduPlanLabel = plan ? plan.label : '';
          } 
          let eduPlanClass = '';
          if (profession.eduPlanId == '1') eduPlanClass = 'edu-plan-gsb';
          else if (profession.eduPlanId == '2') eduPlanClass = 'edu-plan-zsb';
          else if (profession.eduPlanId == '3') eduPlanClass = 'edu-plan-bss';
          else if (profession.eduPlanId == '4') eduPlanClass = 'edu-plan-zss';
          else if (profession.eduPlanId == '5') eduPlanClass = 'edu-plan-ssb';

          // 处理 languageId，支持逗号分隔的多值，兼容 languages 字段
          let languageId = profession.languages || profession.languageId;
          let languageArr = [];
          if (typeof languageId === 'string') {
            languageArr = languageId.split(',').map(v => v.trim()).filter(Boolean);
          } else if (Array.isArray(languageId)) {
            languageArr = languageId;
          } else if (typeof languageId === 'number') {
            languageArr = [String(languageId)];
          }
          // 语言映射
          const langMap = {
            '1': '中文',
            '2': '西班牙语',
            '3': '韩语',
            '4': '英语',
            '5': '俄语',
            // '4': '日语',
            // '5': '英语'
          };
          const languages = languageArr.map(id => langMap[id] ? langMap[id] + '授课' : '').filter(Boolean);

          // 兼容schoolName
          let schoolName = profession.schoolName || profession.university || profession.college || profession.schName || profession.uniName || '';
          // intro截断，优先intro/description/majorIntro/professionIntro
          let intro = profession.intro || profession.description || profession.majorIntro || profession.professionIntro || '';
          if (intro.length > 22) intro = intro.slice(0, 22) + '...';

          return {
            ...profession, // 保留所有原始字段
            ID: profession.id || index,
            chineseName: [ profession.professionName || '未知专业'],
            description: intro || '暂无介绍',
            intro: intro || '暂无介绍',
            eduPlanClass, // 新增
            languages, // 授课语言标签数组
            schoolName // 新增
          }
        });

        // 开学时间筛选
         const startTime = this.data.startTimeValue;
        if (startTime === '1') {
          // 春季开学，只显示 openingDates 包含 '1'
          formattedList = formattedList.filter(item => {
            const dates = Array.isArray(item.openingDates) ? item.openingDates : String(item.openingDates || '').split(',').filter(Boolean);
            return dates.includes('1');
          });
        } else if (startTime === '2') {
          // 秋季开学，只显示 openingDates 包含 '2'
          formattedList = formattedList.filter(item => {
            const dates = Array.isArray(item.openingDates) ? item.openingDates : String(item.openingDates || '').split(',').filter(Boolean);
            return dates.includes('2');
          });
        }
        // 前端再做一次模糊匹配过滤
        // let keyword = this.data.valueNav.trim();
        // if (keyword) {
        //   formattedList = formattedList.filter(item => {
        //     const name = (item.chineseName && item.chineseName[0]) ? item.chineseName[0] : '';
        //     return name.indexOf(keyword) !== -1;
        //   });
        // }
      }

      let keyword = this.data.valueNav.trim();
      formattedList.forEach((elem) => {
        if(elem.chineseName[0]) {
          elem.chineseName = elem.chineseName[0].replace(new RegExp(`${keyword}`, 'gi'), `%%${keyword}%%`).split('%%');
        }
      }
    );
      // 分页累加
      let oldList = this.data.list || [];
      let newList = this.data.pageNum > 1 ? oldList.concat(formattedList) : formattedList;
      // hasMore 判断：本次返回数量等于pageSize才有更多
      let hasMore = formattedList.length === this.data.pageSize;
      this.setData({
        list: newList,
        datas: { list: newList, total: newList.length },
        hasMore
      }, () => {
        // 自动补齐一屏
        wx.createSelectorQuery().select('.school-list-container').boundingClientRect(rect => {
          wx.getSystemInfo({
            success: res => {
              if (rect && rect.height < res.windowHeight && this.data.hasMore && formattedList.length > 0) {
                this.setData({ pageNum: this.data.pageNum + 1 }, this.switchInt);
              }
            }
          })
        }).exec();
      });
      if(formattedList && formattedList.length > 0) {
        let resultText = (this.data.currIndex === 0 || this.data.currIndex === '0') ? `找到${formattedList.length}所院校` : `找到${formattedList.length}个专业课程`;
        wx.showToast({ title: resultText, icon: 'success' });
      } else {
        let noResultText = (this.data.currIndex === 0 || this.data.currIndex === '0') ? '未找到相关院校' : '未找到相关专业课程';
        wx.showToast({ title: noResultText, icon: 'none' });
      }
    }).catch((err) => {
      wx.hideLoading();
      let errorMessage = '搜索失败，请重试';
      if (err.code === 401) errorMessage = '认证失败，请重新登录';
      else if (err.code === 404) errorMessage = '接口不存在，请联系管理员';
      else if (err.message) errorMessage = err.message;
      wx.showToast({ title: errorMessage, icon: 'none' });
    });
  },

  goSchools(e) {
    let schoolId = e.currentTarget.dataset.schoolid;
    wx.navigateTo({
      url: '/pages/schools/schools?schoolId=' + schoolId,
    })
    // 不关闭
    // this.onClose()
  },

  goComments(e) {
    // this.setData({
    //   valueNav: '',
    //   datas: {}
    // })
    let commentId = e.currentTarget.dataset.ids
    wx.navigateTo({
      url: '/pages/commentDetails/commentDetails?commentId=' + commentId,

    })
    // this.onClose()
  },

  goProfession(e) {
    const professionId = e.currentTarget.dataset.professionid;
    const schoolId = e.currentTarget.dataset.schoolid;
    wx.navigateTo({
      url: `/pages/schools/profession?id=${professionId}&schoolId=${schoolId}`,
    });
  },

  onTabsChange(event) {
    // 现在只支持两个标签：0-院校匹配，1-项目匹配
    this.setData({
      currIndex: event.detail.value,
      pageNum: 1, // 重置页码
      pages: 1,
      tabValue: event.detail.value,
      list: [] // 清空列表
    })
    
    // 切换标签页后自动触发搜索
    // 项目匹配(1)：总是自动搜索
    // 院校匹配(0)：也自动搜索，保持一致性
    this.switchInt();
  },

   // 节流搜索
   changeHandle(e) {
    const { value } = e.detail;
    this.setData({
      valueNav: value, // 更新搜索框的值
    });
    
    // 实时搜索功能 - 使用防抖，避免过于频繁的搜索
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    
    this.searchTimer = setTimeout(() => {
      // 延迟500ms后执行搜索，防止用户快速输入时频繁触发
      this.switchInt();
    }, 500);
  },

  onTabsClick(event) {
     
  },

  onStickyScroll(event) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清除搜索定时器，避免内存泄漏
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
      this.searchTimer = null;
    }
  },
  // 过滤HTML标签
  filterHtmlTags(html) {
  if (!html) return '';
  return html.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').trim();
},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 下拉刷新，重置分页
    this.setData({
      pageNum: 1,
      hasMore: true,
      list: []
    }, () => {
      this.switchInt();
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 加载更多
    console.log('[onReachBottom] 当前pageNum:', this.data.pageNum, 'hasMore:', this.data.hasMore);
    if (this.data.hasMore) {
      this.setData({
        pageNum: this.data.pageNum + 1
      }, () => {
        console.log('[onReachBottom] 递增后pageNum:', this.data.pageNum);
        this.switchInt();
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 培养计划下拉框展开事件
  onTrainingPlanOpen() {
    this.setData({
      trainingPlanDropdownOpen: true
    });
  },

  // 培养计划下拉框关闭事件
  onTrainingPlanClose() {
    this.setData({
      trainingPlanDropdownOpen: false
    });
  },

  // 目的地下拉框展开事件
  onDestinationOpen() {
    this.setData({
      destinationDropdownOpen: true
    });
  },

  // 目的地下拉框关闭事件
  onDestinationClose() {
    this.setData({
      destinationDropdownOpen: false
    });
  },

  // 项目匹配 - 培养计划下拉框展开事件
  onProjectTrainingPlanOpen() {
    this.setData({
      projectTrainingPlanDropdownOpen: true
    });
  },

  // 项目匹配 - 培养计划下拉框关闭事件
  onProjectTrainingPlanClose() {
    this.setData({
      projectTrainingPlanDropdownOpen: false
    });
  },

  // 项目匹配 - 目的地下拉框展开事件
  onProjectDestinationOpen() {
    this.setData({
      projectDestinationDropdownOpen: true
    });
  },

  // 项目匹配 - 目的地下拉框关闭事件
  onProjectDestinationClose() {
    this.setData({
      projectDestinationDropdownOpen: false
    });
  },

  // 项目匹配 - 开学时间下拉框展开事件
  onProjectStartTimeOpen() {
    this.setData({
      projectStartTimeDropdownOpen: true
    });
  },

  // 项目匹配 - 开学时间下拉框关闭事件
  onProjectStartTimeClose() {
    this.setData({
      projectStartTimeDropdownOpen: false
    });
  },

  onSearchFocus() {
    this.setData({ searchActive: true });
  },

  // 新增：index页三个文本框点击事件
  onSingaporeBoxTap() {
    wx.navigateTo({ url: '/pages/area/singapore/singapore' });
  },
  onKoreaBoxTap() {
    wx.navigateTo({ url: '/pages/area/korea/korea' });
  },
  onSpainBoxTap() {
    wx.navigateTo({ url: '/pages/area/spain/spain' });
  },
  flagImageError(e) {
    // 可选：图片加载错误处理
    console.log('国旗图片加载失败:', e.detail.errMsg)
  },
})